<!--音频通话 （不支持拖拽）
废弃原因：
当打开语音通话后不能操作其他功能
已优化页面：@/views/voice/voice
-->
<template>
	<div class="contact">
		<audio ref="audioplay" :src="apifun.hrefURL+'/static/14060.mp3'"></audio>
		<el-dialog  
		
			id="voiceblock"
		  :visible.sync="voiceis"
		  width="370px"
		  top="50px"
		  :before-close="voiceisClosefun"
		  :modal-append-to-body="false">
		  <div class="voicemain">
			<div class="voicemain-head">
				<div class="voicemain-headavater">
					<img :src="apifun.URLimg + youMsg.avatar" alt="头像" />
				</div>
				<div class="voicemain-headname">{{ youMsg.realname }}</div>
				<div class="voicemain-headname" v-if="state == 1">正在等待对方接听</div>
				<div class="voicemain-headname" v-if="state == 2">邀请你语音通话</div>
				<div class="voicemain-headname" v-if="state == 3">通话中...</div>
				<div class="voicemain-headname" v-if="state == 4">通话结束</div>
			</div>
			<div class="voicemain-bottonbtn">
				<div class="voicemain-btnequipment" v-if="!iszcTRTC">当前设备浏览器不支持音频功能，请检查设备或转至手机继续语音</div>
				<div class="voicemain-btnequipment" v-if="microphonenum <= 0">未检测到麦克风，请检查设备或转至手机继续语音</div>
				<div class="voicemain-bottonbtnmain marginAuto flex">
					<div class="voicemain-bottonbtneach flex">
						<img style="width:50px;height:50px" @click="exitRoomfun" src="@/assets/chat/stopvoice.png" alt="挂断" />
					</div>
					<div class="voicemain-bottonbtneach flex" v-if="state == 2">
						<img style="width:50px;height:50px" @click="sendcalljtfun" src="@/assets/chat/startvoice.png" alt="接听" />
					</div>
				</div>
			</div>
		  </div>
		</el-dialog>
	</div>
</template>

<script>
	import LibGenerateTestUserSig from '@/utils/lib-generate-test-usersig.min.js';
	import TRTC from 'trtc-sdk-v5';
	import utils from '@/utils/utils';
	export default {
		props:{
			infodataacitem:{
				type:Object,
				default:{}
			},
			statustype:{  // 1拨打方，2接听方
				type:Number,
				default:1
			},
			answer:{
				type:Object,
				default:{}
			}
		},
		data(){
			return {
				state:1, // 1正在等待对方接听 2邀请你语音 3通话中4结束
				sdkAppId:1600046845,
				secretKey:'3c521e02d23c3b687a11bf15daa627dd3f642e89e7d07a9b4cdfd86450cae9f0',
				userInfo:{},
				userId: '',
				youID:'',
				youMsg:{},
				roomId: '',
				userSig:'',
				id:'',  //  消息id
				
				iszcTRTC:false,  // 检测是否支持TRTC
				microphonenum:0,
				microphoneId: String,
				voiceis:true,
				client: null,
			}
		},
		computed:{
			// answerfun(answerdata){
			// 	let extendsdata = this.answer.extends;
			// 	return extendsdata
			// }
		},
		watch:{
			answer(){
				let extendsdata = this.answer.extends;
				if(extendsdata.event == 'calling'){  //  呼叫中
					this.state = 2;
				};
				if (extendsdata.event == 'acceptRtc') {  // 通话
					this.state = 3;
					this.startLocalAudio();
					if(!this.$refs.audioplay.paused){
						this.$refs.audioplay.pause();
					}
				};
				if (extendsdata.event == 'busy') {  // 忙线
					this.$message({
					  message: '忙线中；请稍后在拨',
					  type: 'warning'
					});
					this.state = 4;
					this.client.exitRoom();
					this.voiceis = false;
					this.$emit('fvoiceisfun',false);
					this.client.stopLocalAudio();
					this.roomId = '';
				};
				if(extendsdata.event == 'hangup'){  // 挂断
					this.state = 4;
					this.roomId = '';
					if(!!this.$refs.audioplay){
						this.$refs.audioplay.pause();
					}
					this.voiceis = false;
					this.$emit('fvoiceisfun',false);
				};
			}
		},
		mounted(){
			this.electron.ipcRenderer.send('open-call-window');
			this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
			this.userId = this.userInfo.user_id.toString();
			this.isSupported();  // 检测浏览器是否支持TRTC
			this.getMicrophoneList();  //  获取麦克风设备列表
			this.$refs.audioplay.play();
			if(this.statustype == 1){// 拨打
				this.youMsg = {
					avatar:this.infodataacitem.avatar,
					mobile:this.infodataacitem.account,
					realname:this.infodataacitem.realname,
					user_id:this.infodataacitem.user_id,
				};
				this.youID = this.infodataacitem.user_id;
				this.id = utils.getUuid();
				this.callfun();
			}else{  // 接听
				this.youMsg = {
					avatar:this.answer.fromUser.avatar,
					mobile:this.answer.fromUser.mobile,
					realname:this.answer.fromUser.realname,
					user_id:this.answer.fromUser.user_id,
				};
				this.youID = this.answer.fromUser.user_id;
				this.id = this.answer.strid;
				this.state = 2;
			}
			let arr = [this.userId, this.youID];
			arr.sort((a, b) => a - b);
			this.roomId = arr[0] + '-' + arr[1];
			// // 音频
			this.initClient();
		},
		methods:{
			initClient(){  // 初始化
				// const userSigGenerator = new LibGenerateTestUserSig(this.sdkAppId, this.secretKey, 604800);
				// this.userSig = userSigGenerator.genTestUserSig(this.userId);
				this.apifun.$post('/pc/im/getUserSign',{}).then((res)=>{
					if(res.code ==  200){
						let datas = res.data;
						this.userSig = datas;
						let tetcdata = {
							mode: 'rtc',
							sdkAppId: this.sdkAppId,
							userId: this.userId,
							userSig: datas,
						};
						this.client = TRTC.create(tetcdata);
						this.enterRoomfun();
						this.handleClientEvents();
					}
				})
			},
			enterRoomfun(){ // 进房
				let enterRoom = {
					strRoomId: this.roomId,
					sdkAppId:this.sdkAppId,
					userId: this.userId,
					userSig :this.userSig,
					autoReceiveAudio:true
				}
				this.client.enterRoom(enterRoom);
			},
			exitRoomfun(){  // 退出房间
				let code = this.state == 3 ? 906 : this.state == 2 ? 903 : 902;
				this.state = 4;
				let sendData = {
					toContactId:this.youID,
					event:'hangup',
					id:this.id,
					status:this.statustype,
					code:code,
				}
				this.apifun.$post('/pc/im/sendToMsg',sendData).then((res)=>{
					// console.log('挂断',res.data)
					if(res.code ==  200){
						let datas = res.data;
						this.$emit('fvoiceisfun',datas);
					};
					this.client.exitRoom();
					this.client.stopLocalAudio();
					this.roomId = '';
					this.voiceis = false;
					if(this.$refs.audioplay){
						this.$refs.audioplay.pause();
					}
					
				});
			},
			callfun(){  // 拨打
				let sendData = {
					toContactId: this.youID,
					id: this.id,
					status:1,  //  1拨打方 2接听方
					code: 901,
					event: 'calling'
				}
				this.state = 1;
				this.apifun.$post('/pc/im/sendToMsg',sendData).then((res)=>{
					// console.log(res)
					if(res.code ==  200){}
				})
			},
			sendcalljtfun(){  // 接听
				let sendData = {
					toContactId: this.youID,
					id: this.id,
					status:2,  //  1拨打方 2接听方
					code: 901,
					msg_id:this.answer.msg_id,
					event:'acceptRtc'
				}
				this.state = 3;
				this.startLocalAudio()
				this.apifun.$post('/pc/im/sendToMsg',sendData).then((res)=>{
					// console.log(res)
					if(res.code ==  200){
						if(!this.$refs.audioplay.paused){
							this.$refs.audioplay.pause();
						}
					}
				})
			},
			async startLocalAudio() {
				console.log('1111111111111看看语音',this.client);
				this.client.enableAudioVolumeEvaluation(500);
				// setSystemAudioLoopbackVolume
				this.client.setRemoteAudioVolume('*',150);
				this.client.startLocalAudio();
				// this.client.updateLocalAudio({ mute: false });
			},
			handleClientEvents() {  // 监听事件
				let that = this;
				// client.on('peer-leave')   远端退房
				this.client.on('error', (error) => {
				  console.error('on-error--',error);
				});
				this.client.on('connection-state-changed', (event) => {  //  'DISCONNECTED'：连接断开		'CONNECTING'：正在连接中		'CONNECTED'：已连接
				    const prevState = event.prevState;
				    const curState = event.state;
					if(prevState == 'CONNECTING' && curState == "DISCONNECTED"){  // 失败
						this.exitRoomfun()
					}
					if(prevState == 'CONNECTED' && curState == "DISCONNECTED"){  // 失败
						this.exitRoomfun()
					}
				});
				this.client.on('remote-user-exit', (event) => {  // 退出房间
				  this.client.exitRoom();
				  this.client.stopLocalAudio();
				  this.roomId = '';
				  this.voiceis = false;
				  this.$emit('fvoiceisfun',false);
				});
				
				this.client.on('remote-audio-available', (event) => {  // 收到远端进入房间
				  console.error('远端用户发布音频--',event);
				  // that.state = 3;
				  // this.startLocalAudio();
				  // this.$refs.audioplay.pause();
				});
				this.client.on('remote-audio-unavailable', (event) => {  // 远端退出房间
				  console.error('远端用户关闭音频--',event);
				   that.state=4;
				  this.exitRoomfun();
				  this.voiceis = false;
				  this.$emit('fvoiceisfun',false);
				});
			},
			async getMicrophoneList(){ // 检测麦克风设备列表
				const microphoneList = await TRTC.getMicrophoneList();
				if (microphoneList[0] && microphoneList[0].getCapabilities) {
					const { channelCount } = microphoneList[0].getCapabilities();
					this.microphonenum = channelCount.max
				}
			},
			async isSupported(){  // 检测浏览器是否支持TRTC
				TRTC.isSupported().then((checkResult) => {
				  if(!checkResult.result) {
				     console.log('checkResult', checkResult.result, 'checkDetail', checkResult.detail);
				     // SDK 不支持当前浏览器，引导用户使用最新版的 Chrome 浏览器。
					 this.iszcTRTC = false
				  }else{
					  this.iszcTRTC = true
				  }
				});
			},
			voiceisClosefun(){
				this.exitRoomfun();
				if(!this.$refs.audioplay.paused){
					this.$refs.audioplay.pause();
				}
				this.voiceis = false;
				this.$emit('fvoiceisfun',false);
			}
		},
		beforeDestroy() {
			if(!this.$refs.audioplay.paused){
				this.$refs.audioplay.pause();
			}
			this.client.off('*');
			this.exitRoomfun();
			this.voiceis = false;
			this.$emit('fvoiceisfun',false);
		},
		// destroyed() {
		// 	this.client.off('*');
		// },
	}
</script>
<style>
	#voiceblock .el-dialog__header{
		padding:50px 0 0;
	}
	#voiceblock .el-dialog__body{
		padding: 0;
	}
</style>
<style scoped lang="scss">
	.voicemain{
		position: relative;
		width: 370px;
		height: 550px;
		background-color:#fff;
	}
	.voicemain-head{
		margin-top:20px;
		width:100%;
		.voicemain-headavater{
			width:100px;
			height: 100px;
			margin: auto;
			img{
				width:100px;
				height: 100px;
			}
		}
		.voicemain-headname{
			line-height: 40px;
			font-size: 14px;
			text-align: center;
			color:#333;
		}
	}
	.voicemain-bottonbtn{
		position: absolute;
		width: 100%;
		bottom: 20px;
		z-index:0;
		.voicemain-btnequipment{
			width: 70%;
			text-align: center;
			padding: 10px;
			background-color:#F4F4F4;
			border-radius: 8px;
			color: #333;
			font-size: 14px;
			line-height: 20px;
			margin:0 auto 20px;
		}
		.voicemain-bottonbtnmain{
			width: 90%;
			justify-content: space-around;
			.voicemain-bottonbtneach{
				width: 50px;
				height: 50px;
				border-radius: 50%;
			}
		}
		
	}
</style>